package edu.pdx.cs.cs542s07.minichess;

import java.util.ArrayList;
import java.util.Random;

class BoardController {
	
	private NegamaxFactory negamaxfac = new NegamaxFactory();

	void humanMove(String moveString, Board board) 
	throws IllegalMoveException {
		// parse string
		char[] cs = moveString.toCharArray();
		Square from = new Square((cs[1] - '1'),(cs[0] - 'a'));
		Square to = new Square((cs[4] - '1'),(cs[3] - 'a'));
		
		// sanity checks
		if (from.col < 0 || from.col >= Board.NUMBER_OF_COLUMNS 	||
				to.col < 0 || to.col >= Board.NUMBER_OF_COLUMNS 	||
			from.row < 0 || from.row >= Board.NUMBER_OF_ROWS		||
				to.row < 0 || to.row >= Board.NUMBER_OF_ROWS		||
				cs[2] != '-') {
			throw new IllegalMoveException(moveString + " is not a legitimate move string.");
		}
		
		// execute move
		Move newMove = new Move(from, to); 
		board.move(newMove);
		
	}
	
	/**
	 * Does a one-move look ahead to find the immeidately best move
	 * @param board
	 * @return
	 */
	void randomImmediateBestMove(Board board) {
		MoveFactory factory = new MoveFactory();
		ArrayList<Move> moves = factory.generateScoredMoves(board);
		ArrayList<Move> bestMoves = new ArrayList<Move>();
		int lowestScore = ScoreFactory.YOU_WIN;
		for(Move m:moves) {
			if (m.getScore() < lowestScore) {
				lowestScore = m.getScore();
				bestMoves.add(m);
				// debug
				
			} else if (m.getScore() > lowestScore) {
				break;
			} else {
				bestMoves.add(m);
			}
		}
		Random random = new Random();
		Move moveToExecute = bestMoves.get(random.nextInt(bestMoves.size()));
		
		try {
			board.move(moveToExecute);
		} catch (IllegalMoveException e) {
			// This should never, ever happen. Ever. Seriously.
			e.printStackTrace();
			// So if it ever DOES happen, we need to quit immediately and figure out what's going on.
			System.exit(0);
		}
	}

	void negamaxBestMove(Board board) {
		Move moveToExecute = negamaxfac.negamax(board);		
		try {
			board.move(moveToExecute);
		} catch (IllegalMoveException e) {
			// This should never, ever happen. Ever. Seriously.
			e.printStackTrace();
			// So if it ever DOES happen, we need to quit immediately and figure out what's going on.
			System.exit(0);
		}
	}



}
